<?php
declare (strict_types = 1);

namespace app\user\model;

use think\facade\Db;
use think\Model;

/**
 * @mixin \think\Model
 */
class BalanceLog extends Model
{
    public $page = '';//分页数据
    public $count = '';//数据总数
    public $error = '';//报错

    /*
     * 获取用户余额记录
     */
    public function getBalances($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            $type = isset($data['type'])&&!empty($data['type']) ? $data['type'] : 1;
            $where = ['b.uid' => $id,'b.is_delete'=>0,'b.is_sys'=>0];

            $limit = isset($data['limit'])&&!empty($data['limit']) ? $data['limit'] : 15;//每页显示数据
            $query = ['page' => (isset($data['page']) ? $data['page'] : 1)];//分页参数
            $field1 = "b.uid,CONCAT(CASE  WHEN b.type=1 THEN '充值' WHEN b.type=2 THEN '消费' ELSE '退款' END,IF(o.order_sn,CONCAT(' (订单号:',o.order_sn,')'),'')) as type,b.num as balance,b.add_time";
            if($type == 1){
                #收入，需要连表user_cash，balance_log查询
                $balances = $this->alias('b')->join('order o','o.id=b.relation_id','left')->field($field1)->whereIn('b.type','1,3')->where($where)->buildSql();
                $ucash = Db::name('user_cash')->where(['uid'=>$id,'type'=>1,'status'=>3,'is_delete'=>0])->field('uid,"喵呗兑换" as type,gold as balance,add_time')->unionAll([$balances])->buildSql();
                $item = Db::table($ucash)->alias('union')->order('add_time desc')->paginate($limit, false, array('query'=>$query));
            }else
                $item = $this->alias('b')->join('order o','o.id=b.relation_id','left')->field($field1)->where('b.type',2)->where($where)->order('add_time desc')->paginate($limit, false, array('query'=>$query));

            $balance = empty($item) ? array():$item->toArray();
            $wallet = (new UserWallet())->getWallet($id);
            if(!empty($balance['data']))
                foreach($balance['data'] as $k=>$v){
                    $balance['data'][$k]['balance'] = getformat($v['balance']);
                    $balance['data'][$k]['add_time'] = date('Y-m-d H:i',$v['add_time']);
                }
            $data = [
                'wallet'=>$wallet,
                'balanceList'=>$balance
            ];
            return $data;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }
}
